#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/1/2 18:36
# @Author  : leon yan
# @Site    : 
# @File    : Globalist.py
# @Software: PyCharm
import csv
import json
import socket
from enum import Enum

from configobj import ConfigObj
from lib.qsqledit import QSQL
from lib.fileprocess import cfgProcess


class QAlarmList(Enum):
    a = "1"
    b = "2"
    c = "3"


global global_config, global_plc_config, global_dict, global_var


# 1 initial
def init():
    globals()["global_config"] = ConfigObj(r".\api\cfg.ini", encoding='utf-8')
    globals()["global_plc_config"] = ConfigObj(r".\api\plc.ini", encoding='utf-8')
    globals()["global_var"] = cfgProcess.get_cfg_JsonData(r".\api\.variableCfg")
    globals()["global_dict"] = {}

    '''obj'''
    set_value("obj_UpdateThread", None)

    '''与PL相关--总体的'''
    set_value('xHasGlobalTrip', 0)
    set_value('xAutoStatus', 0)

    '''其他变量'''
    """
    当前计算机信息显示
    """
    pcName = str(socket.getfqdn(socket.gethostname()))  # get name
    aa = pcName.split('.')
    try:
        pcAddress = socket.gethostbyname(aa[0])  # get ip
    except BaseException as e:
        pcAddress = "127.0.0.1"
        print("err:", e)
    set_value("pcName", pcName)
    set_value("pcAddress", pcAddress)


def systemVariable():
    pass


def deviceInitial():
    """"""
    with open(r".\api\PlcAddress.csv", encoding="gbk") as f:
        f_csv = csv.reader(f)
        lstRow = []
        i = 0
        for row in f_csv:
            if i > 0:
                lstRow.append(row)
            i += 1
        # 4 ==>run, 6==>alarm, 8==>emergency
        for i in range(len(lstRow)):
            if lstRow[i][5]:
                aa = int(lstRow[i][5])
            else:
                aa = 0
            globals()["global_var"]["PlcAddress_running"][str(i)] = [lstRow[i][4], aa]
            if lstRow[i][7]:
                aa = int(lstRow[i][7])
            else:
                aa = 0
            globals()["global_var"]["PlcAddress_alarm"][str(i)] = [lstRow[i][6], aa]
            if lstRow[i][9]:
                aa = int(lstRow[i][9])
            else:
                aa = 0
            globals()["global_var"]["PlcAddress_emergency"][str(i)] = [lstRow[i][8], aa]

        # print(globals()["global_var"]["PlcAddress_running"])

    """设备列表"""
    aFields = ['Num', "Code", 'Name', 'Ip', "Power", "Descriptions"]
    obj = QSQL("Device", "", "order by num", aFields)
    rdData = obj.showLst()
    lst = json.loads(rdData)
    deviceDict = {}
    ipTmpDict = {}
    if lst:
        j = 0
        for i in range(len(lst)):
            if lst[i][3]:
                deviceDict[i] = [lst[i][1], lst[i][2], lst[i][3], 0]
            else:
                deviceDict[i] = [lst[i][1], lst[i][2], lst[i][3], 0]

            if lst[i][3]:
                ipTmpDict[j] = [lst[i][3], 0, lst[i][1] + "_" + lst[i][2]]
                j += 1

    globals()["global_var"]["deviceNum"] = len(lst)
    globals()["global_var"]["deviceDict"] = deviceDict  # 主页的右侧显示["code, name, ip/none, 0/1"]
    globals()["global_var"]["deviceIpDict"] = ipTmpDict  # Ip地址及顺序（顺序从0开始）
    for i in range(len(lst)):
        globals()["global_var"]["bEmergencyStopList"].append(0)
        globals()["global_var"]["bAlarmList"].append(0)
        globals()["global_var"]["bRunningList"].append(0)
    for i in range(len(ipTmpDict)):
        globals()["global_var"]["send_plc_pool"][str(i)] = []

    """生产日志"""
    aFields = ['Id', "LogTime", 'TodayInitPower', 'TodayInitAmount', "Operator"]
    obj = QSQL("ProductLog", "", "order by LogTime desc", aFields)
    rdData = obj.showLst()
    lst = json.loads(rdData)
    aa = {}
    aaLen = len(lst)
    for i in range(5):
        if i < aaLen:
            aa[i] = [lst[i][1], lst[i][2], lst[i][3]]
        else:
            aa[i] = ["", 0, 0]
    aa1 = []
    aa2 = []
    for k, v in aa.items():
        aa1.append(v[1])
        aa2.append(v[2])
    global_var["chartMonitor"]["dayAmount"] = aa1
    global_var["chartMonitor"]["dayPower"] = aa2

    ''''''
    aa = cfgProcess.get_cfg_JsonData(r".\api\.powerCfg")["save_power_meter_ip"]
    global_var["watt_hour_meter_ip"] = aa

def initialPlc():
    """"""
    aa = global_var["Plc_read_area"]["data_rdArea1"]
    aa1 = aa["dType"]
    for k, v in aa1.items():
        if "?" not in k:
            for i in range(v[1], v[2] + 1):
                bb = []
                for j in range(v[3]):
                    bb.append(0)
                global_var["Plc_read_area"]["data_rdArea1"]["dArea"][str(i)] = [v[4], v[0], bb]

    aa = global_var["Plc_read_area"]["data_rdArea2"]
    aa1 = aa["dType"]
    for k, v in aa1.items():
        if "?" not in k:
            for i in range(v[1], v[2] + 1):
                bb = []
                for j in range(v[3]):
                    bb.append(0)
                global_var["Plc_read_area"]["data_rdArea2"]["dArea"][str(i)] = [v[4], v[0], bb]

    aa = global_var["Plc_read_area"]["data_rdArea3"]
    aa1 = aa["dType"]
    for k, v in aa1.items():
        if "?" not in k:
            for i in range(v[1], v[2] + 1):
                bb = []
                for j in range(v[3]):
                    bb.append(0)
                global_var["Plc_read_area"]["data_rdArea3"]["dArea"][str(i)] = [v[4], v[0], bb]

    aa = global_var["Plc_read_area"]["data_rdArea4"]
    aa1 = aa["dType"]
    for k, v in aa1.items():
        if "?" not in k:
            for i in range(v[1], v[2] + 1):
                bb = []
                for j in range(v[3]):
                    bb.append(0)
                global_var["Plc_read_area"]["data_rdArea4"]["dArea"][str(i)] = [v[4], v[0], bb, v[5]]

    '''云对接'''
    aa = []
    for i in range(96):
        aa.append(0)
    if aa:
        global_var["monitorVar"]["cloudBitData"] = aa

    aa = []
    for i in range(40):
        aa.append(0)
    if aa:
        global_var["monitorVar"]["cloudWordData"] = aa


# 2 Plc通信变量
def initial_cfg():
    # Pc
    aa = global_config['Pc']["socketPort"]
    set_value("socketPort", int(aa))

    # '''QRCode'''
    aa = global_config['QRCode']["version"]
    set_value("qr_version", int(aa))
    aa = global_config['QRCode']["size"]
    set_value("qr_size", int(aa))
    aa = global_config['QRCode']["error"]
    set_value("qr_error", int(aa))

    # '''working'''
    aa = global_config['working']["PowerTime"]
    globals()["global_var"]["monitorVar"]["PowerTime"] = int(aa)
    aa = global_config['working']["WorkTime"]
    globals()["global_var"]["monitorVar"]["WorkTime"] = int(aa)
    aa = global_config['working']["AlarmTime"]
    globals()["global_var"]["monitorVar"]["AlarmTime"] = int(aa)

    # globals()["global_var"]["watt_hour_meter_ip"] = bb


def List2ListInt(theStr):
    aa = theStr
    for i in range(len(aa)):
        aa[i] = int(aa[i])
    return aa


# 3 Plc通信变量
def initPlcModBus():
    aa = []
    for i in range(13):
        aa.append(0)
    set_value("bEnablePlcWrite", 0)
    set_value("bPlcWriting", 0)
    for i in range(10):
        set_value("bPlcWriting_" + str(0), 0)  # 多PLC时用这个标志位


def set_value(name, value):
    global_dict[name] = value


def get_value(name, defValue=None):
    try:
        return global_dict[name]
    except KeyError:
        return defValue
